package com.change.zh.ffmpegdo.push;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * 任务消息输出处理器
 */
public class CommandConsoleThread extends Thread {

    private volatile boolean finished = false;   // ① volatile条件变量
    private BufferedReader bufferedReader;
    private String id;


    public CommandConsoleThread(InputStream is, String id) {
        bufferedReader = new BufferedReader(new InputStreamReader(is));
        this.id = id;
    }

    /**
     * 线程销毁方法，安全的关闭线程
     */
    public void commandConsoleThreadDestroy() {
        finished = true;    // ② 发出停止信号
        Thread.currentThread().interrupt();
    }

    /**
     * 执行输出线程
     * 当④处的代码阻塞于wait()或sleep()时，线程不能立刻检测到条件变量。因此②处的代码最好同时调用interrupt()方法。
     */
    @Override
    public void run() {
        while (!finished) {    // ③ 检测条件变量
            // ④业务代码
            String console = null;
            try {
                System.out.println("CommandConsoleThread     "+"  [开始打印] :" + id);
                while ((console = bufferedReader.readLine()) != null) {
                    if (console.indexOf("[rtsp") != -1) {
                        System.out.println("CommandConsoleThread    :发生网络异常丢包 "+this.getId()+"**"+this.getName()+"  " + console);
                    }else if(console.indexOf("frame=")!=-1){
                        System.out.println("CommandConsoleThread    : return line :"+this.getId()+"**"+this.getName()+"  " + console);
                    }
                }
            } catch (IOException e) {
                System.err.println("CommandConsoleThread   [0>>before] :" + "IOE关闭[" + this.getId() + "]线程");
                commandConsoleThreadDestroy();
                System.err.println("CommandConsoleThread   [1>>after] :" + "IOE关闭[" + this.getId() + "]线程");
            } finally {
                if (finished && this.isAlive()) {
                    System.err.println("CommandConsoleThread   [0>>before] :" + "finally关闭[" + this.getId() + "]线程");
                    commandConsoleThreadDestroy();
                    System.err.println("CommandConsoleThread   [1>>after] :" + "finally关闭[" + this.getId() + "]线程");
                }
            }
        }
    }
}
